package com.android.juliomedina.parser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import com.android.juliomedina.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * 
 * @author globussoft
 */
public class Fitness_actvity extends ListActivity implements Runnable {
	/** Called when the activity is first created. */

	private ProgressDialog dialog = null;
	String[] links = { "http://www.juliomedina.com/fitness/feed/",
			"http://www.juliomedina.com/coachhelp/feed/" };
	String[] categories = { "Fitness", "Coachhelp" };
	String link;
	String res;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Intent intent = new Intent(Fitness_actvity.this,
					Fitness_FeedList.class);
			res = res.replaceAll("&", "&amp;");
			intent.putExtra("results", res);
			startActivity(intent);
		}
	};

	private String convertXML(String src) {
		KXmlParser parser = null;
		String name;
		String result = "";
		boolean collect = false;
		try {
			parser = new KXmlParser();
			InputStreamReader isr = new InputStreamReader(
					new ByteArrayInputStream(src.getBytes("UTF-8")));
			parser.setInput(isr);
			while (parser.next() != XmlPullParser.END_DOCUMENT) {
				if (parser.getEventType() == XmlPullParser.START_TAG) {
					name = parser.getName();
					if (name.equals("item")) {
						result = result + "<item>";
						collect = true;
					} else if (name.equals("title") && collect == true) {
						result = result + "<title>" + parser.nextText();
					} else if (name.equals("description") && collect == true) {
						String temp = parser.nextText();
						String s1 = ReplaceAllHtmlTage.GetOnlyData(temp);
						result = result + "<description>" + s1;
					} else if (name.equals("content:encoded")
							&& collect == true) {
						String temp = parser.nextText();
						String youtube = "NA";
						int youtubeStart = temp.indexOf("<iframe");
						if (youtubeStart >= 0) {
							youtubeStart = temp.indexOf("src=\"", youtubeStart);
							int youtubeEnd = temp.indexOf("\"", youtubeStart
									+ "src=\"".length());
							youtube = temp.substring(
									youtubeStart + "src=\"".length(),
									youtubeEnd);
						}
						String image = "NA";
						int imageStart = temp.indexOf("<img");
						if (imageStart >= 0) {
							imageStart = temp.indexOf("src=\"", imageStart);
							int imageEnd = temp.indexOf("\"", imageStart
									+ "src=\"".length());
							image = temp.substring(
									imageStart + "src=\"".length(), imageEnd);
						}
						String s2 = ReplaceAllHtmlTage.GetOnlyData(temp);
						result = result + "<content:encoded>" + s2 + "@@@"
								+ youtube + "@@@" + image;
					} else if (name.equals("link") && collect == true)
						result = result + "<link>" + parser.nextText();
					else if (name.equals("pubDate") && collect == true)
						result = result + "<pubDate>" + parser.nextText();
				}
				if (parser.getEventType() == XmlPullParser.END_TAG) {
					name = parser.getName();
					if (name.equals("item")) {
						result = result + "</item>";
						collect = false;
					} else if (name.equals("title") && collect == true)
						result = result + "</title>";
					else if (name.equals("description") && collect == true)
						result = result + "</description>";
					else if (name.equals("content:encoded") && collect == true)
						result = result + "</content:encoded>";
					else if (name.equals("link") && collect == true)
						result = result + "</link>";
					else if (name.equals("pubDate") && collect == true)
						result = result + "</pubDate>";
				}
			}
			if (dialog != null)
				dialog.dismiss();
			return result;
		} catch (Exception e) {
			AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
			alertbox.setMessage(e.getMessage());
			alertbox.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							if (dialog != null)
								dialog.dismiss();
						}
					});
			alertbox.show();
		}
		return null;
	}

	private String download(String urlString) {
		InputStream in = null;
		byte[] data = null;
		URLConnection conn = null;
		try {
			URL url = new URL(urlString);
			conn = url.openConnection();

			if ((conn instanceof HttpURLConnection)) {
				HttpURLConnection httpConn = (HttpURLConnection) conn;
				httpConn.setAllowUserInteraction(false);
				httpConn.setInstanceFollowRedirects(true);
				httpConn.setRequestMethod("GET");
				httpConn.connect();
				if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					in = httpConn.getInputStream();
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					int c;
					while ((c = in.read()) > -1)
						baos.write(c);
					data = baos.toByteArray();
					baos.close();
					in.close();
					String str = new String(data);
					System.out.println(str);
					return str;
				} else {
					return ("Error reading data");
				}
			}
		} catch (Exception ex) {
			return ("Error in connection");
		} finally {
			try {
				if (conn != null) {
					conn = null;
				}
				if (in != null) {
					in.close();
					in = null;
				}

			} catch (IOException ex) {
				return ("Error: " + ex.getMessage());
			}
		}
		return null;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setListAdapter(new ArrayAdapter<String>(this,
				R.layout.simple_list_item_1, categories));

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1: {
			dialog = new ProgressDialog(Fitness_actvity.this);
			dialog.setMessage("Please wait...Dowloading data...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		link = links[position];
		showDialog(1);
		Thread t = new Thread(Fitness_actvity.this);
		t.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		res = download(link);
		res = convertXML(res);
		handler.sendEmptyMessage(0);
	}
}